<!--
 * @Description: 你的代码我的心
 * @Author: GGB
 * @Date: 2022-01-26 10:17:18
 * @LastEditors: GGB
 * @LastEditTime: 2022-01-26 14:04:43
-->
<template>
  <PageWrapper title="修改当前用户密码" content="修改成功后会自动退出当前登录！">
    <div class="py-8 bg-white flex flex-col justify-center items-center">
      <BasicForm @register="register" />
      <div class="flex justify-center">
        <a-button @click="resetFields"> 重置 </a-button>
        <a-button class="!ml-4" type="primary" @click="handleSubmit"> 确认 </a-button>
      </div>
    </div>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { PageWrapper } from '/@/components/Page';
  import { BasicForm, useForm } from '/@/components/Form';
  import { updateAdminAccount, getAdminInfo } from '/@/api/sys/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { formSchema } from './pwd.data';
  import { UpdateAdminParams } from '/@/api/sys/model/userModel';
  import { onMounted } from 'vue';
  const [register, { validate, resetFields, setFieldsValue }] = useForm({
    size: 'large',
    labelWidth: 100,
    showActionButtonGroup: false,
    schemas: formSchema,
  });

  const initForm = async () => {
    const data = await getAdminInfo();
    const { user_name } = data.userInfo;
    user_name && setFieldsValue({ user_name });
  };
  onMounted(() => {
    initForm();
  });

  const handleSubmit = async () => {
    try {
      const values = await validate();
      delete values.confirmPassword;
      const { createMessage } = useMessage();
      let params = { form: values } as UpdateAdminParams;
      updateAdminAccount(params)
        .then(({ code, message }) => {
          code === 0 && createMessage.success(message);
        })
        .catch(() => {
          createMessage.error('修改失败');
        })
        .finally(() => {
          initForm();
        });
    } catch (error) {}
  };
</script>
